package com.eece411.project.p2;

import java.util.Hashtable;
import java.util.Map;

public class DataStore implements Instance{
	// Definition of the max size
	private static final int MAX_SIZE = 40000;
	private String onHost;
	// DataStructure
	private Map<String, Data> map = new Hashtable<String, Data>(MAX_SIZE);
	
	// Constructor --- Not use now
	public DataStore(String hostname) {
		onHost = hostname;
		System.out.println("Latency : -1");
	}
	
	// Transform the key in bytes to a string. Easier to handle
	private String key2String(byte[] key){
		return new String(key);	
	}
	
	// Basic commande to the datastore
	// put -> check if full if ok return true else false
	public boolean put(byte[] key,byte[] data, boolean isReplication){
		if(map.size()<MAX_SIZE){
			map.put(this.key2String(key), new Data(data));
			return true;
		} else {
			return false;
		}
	}
	//get -> check if in the datastore if ok return
	public byte[] get(byte[] key){
		if(map.containsKey(this.key2String(key))){
			return map.get(this.key2String(key)).getData();
		} else {
			return null;
		}
	}
	// put -> check if exist if ok return true else false
	public boolean remove(byte[] key, boolean isReplication){
		if(map.containsKey(this.key2String(key))){
			map.remove(this.key2String(key));
			return true;
		} else {
			return false;
		}
	}
	// return if exist in datastore
	public boolean containsKey(byte[] key){
		return map.containsKey(this.key2String(key));
	}

	@Override
	public int getLatency() {
		return -1;
	}

	@Override
	public int compareTo(Instance instance) {
		return instance.getLatency()-this.getLatency();
	}

	@Override
	public boolean equals(String s) {
		return this.onHost.equals(s);
	}
}
